package me.firstapp.weixin.controller.transfer;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.SystemConfig;
import me.firstapp.common.utils.WeiXinConfig;
import me.firstapp.module.weixin.jinbi.JinBiAccount;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.transfer.TransferMember;
import me.firstapp.module.weixin.transfer.TransferMemberProduct;
import me.firstapp.module.weixin.transfer.TransferMemberRecord;
import me.firstapp.service.weixin.account.JinBiAccountService;
import me.firstapp.service.weixin.member.MemberService;
import me.firstapp.service.weixin.transfer.TransferMemberProductService;
import me.firstapp.service.weixin.transfer.TransferMemberRecordService;
import me.firstapp.service.weixin.transfer.TransferMemberService;
import me.firstapp.weixin.controller.base.BaseController;

@Controller
public class TransferController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(TransferController.class);

	@Autowired
	private MemberService memberService;

	@Autowired
	private TransferMemberService transferMemberService;

	@Autowired
	private TransferMemberProductService transferMemberProductService;

	@Autowired
	private TransferMemberRecordService transferMemberRecordService;

	@Autowired
	private JinBiAccountService jinBiAccountService;

	@Autowired
	private WeixinProxy weixinProxy;

	@RequestMapping("/page/transferApplyPage.htm")
	public ModelAndView showTransferApplyPage(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		String openId = getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		Long fans = memberService.findTotalFansCounts(openId);
		modelMap.put("fans", fans);
		Long transers = transferMemberService.findMemberTransferCounts(member.getId());
		modelMap.put("transers", transers);
		modelMap.put("max", 100);
		modelMap.put("min", 1);
		modelMap.put("level", member.getVipLevel());
		return new ModelAndView("transfer/transferApply", modelMap);
	}

	@RequestMapping("/page/transferApplySuccess.htm")
	public ModelAndView showTransferApplySuccessPage(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		super.getCurrentLoginOpenId(request, response);
		return new ModelAndView("transfer/transferSuccess", modelMap);
	}

	@RequestMapping("/page/transferList.htm")
	public ModelAndView showTransferMemberListPage(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		super.getCurrentLoginOpenId(request, response);
		return new ModelAndView("transfer/transferMemberList", modelMap);
	}

	@RequestMapping("/page/getTransferMemberProductListData.do")
	public void getTransferMemberProductListData(@RequestParam(defaultValue = "1") int pageIndex,
			@RequestParam(defaultValue = "20") int pageSize, HttpServletRequest request, HttpServletResponse response) {
		ListObject<TransferMemberProduct> result = new ListObject<>();
		try {
			super.getCurrentLoginOpenId(request, response);
			List<TransferMemberProduct> transferMemberProducts = transferMemberProductService
					.findTransferMemberProducts(pageIndex, pageSize);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setItems(transferMemberProducts);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/addTransferProduct.do")
	public void addTransferProduct(Integer counts, BigDecimal amount, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			if (null == counts || null == amount) {
				throw new ServiceException(StatusHouse.COMMON_PARAMETER_ERROR);
			}
			String openId = getCurrentLoginOpenId(request, response);
			Member member = memberService.findMemberByOpenId(openId);
			if (Member.VIP_LEVEL_HIGHT == member.getVipLevel()) {
				throw new ServiceException("error", "只有会员和粉丝才可转让用户");
			}
			if (counts < 1) {
				throw new ServiceException("error", "转让数量最少为1个");
			}
			List<TransferMember> transferMembers = transferMemberService.findTransferMembers(member.getId(),
					TransferMember.STATUS_NORMAL);
			if (counts > transferMembers.size()) {
				throw new ServiceException("error", "转让数量不能大于可转让总数");
			}
			if (counts > 500) {
				throw new ServiceException("error", "单次转让数量不能超过500");
			}
			int max = counts * 100;
			double a = amount.subtract(new BigDecimal(max)).setScale(2, RoundingMode.HALF_UP).doubleValue();
			if (a > 0) {
				throw new ServiceException("error", "本次转让金额不能超过" + max);
			}
			int min = counts * 1;
			double b = amount.subtract(new BigDecimal(min)).setScale(2, RoundingMode.HALF_UP).doubleValue();
			if (b < 0) {
				throw new ServiceException("error", "本次转让金额不能小于" + min);
			}
			TransferMemberProduct transferMemberProduct = transferMemberProductService
					.executeAddTransferMemberProduct(openId, amount, counts);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);

			try {
				TemplateMessage tplMessage = new TemplateMessage(openId,
						WeiXinConfig.WEIXIN_TRANSFER_MEMBER_TEMPLATE_ID,
						SystemConfig.mServerUrl + "/page/transferList.htm");
				tplMessage.pushHead("").pushTail("")
						.pushItem("first", member.getName() + "，您转让的" + counts + "个用户已成功提交，等待买家接收")
						.pushItem("keyword1", transferMemberProduct.getId() + "")
						.pushItem("keyword2", DateUtils.getNowStr("yyyy-MM-dd HH:mm:ss"))
						.pushItem("remark", "买家接收后，您设置的费用【" + amount + "贝币】直接作为您的收入进入您的贝币账户。");
				TmplApi tmplApi = new TmplApi(weixinProxy.getTokenManager());
				String sendResult = tmplApi.sendTmplMessage(tplMessage);
				logger.info("消息模板【" + WeiXinConfig.WEIXIN_TRANSFER_MEMBER_TEMPLATE_ID + "】发送消息返回结果：" + sendResult);
			} catch (WeixinException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/addMEmberTransferRecord.do")
	public void addMEmberTransferRecord(Long transferMemberProductId, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<TransferMemberRecord> result = new SingleObject<>();
		try {
			if (null == transferMemberProductId) {
				throw new ServiceException(StatusHouse.COMMON_PARAMETER_ERROR);
			}
			String openId = getCurrentLoginOpenId(request, response);
			TransferMemberRecord transferMemberRecord = transferMemberRecordService
					.executeAddTransferMemberRecord(openId, transferMemberProductId);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setObject(transferMemberRecord);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/confirmTransfer.htm")
	public ModelAndView showConfirmTransferPage(String recordNo, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		String openId = super.getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		if (null == member) {
			throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
		}
		JinBiAccount jinBiAccount = jinBiAccountService.findJinBiAccountByCardNoAndOpenId(member.getCardNo(), openId);
		modelMap.put("jbalance", jinBiAccount.getBalance());
		TransferMemberRecord transferMemberRecord = transferMemberRecordService.findByOpenIdAndRecordNo(openId,
				recordNo);
		modelMap.put("transferMemberRecord", transferMemberRecord);
		return new ModelAndView("transfer/confirmTransferRecord", modelMap);
	}
}
